const express = require('express')

const BookModel = require('../models/BookModel')

const router = express.Router()

router.get('/',async(req,res)=>{
    try{
     const data = await BookModel.find()
     res.json({
        status:'3000',
        data,
        message:'获取列表成功'
     })
       
    }catch(error){
    res.json({
        status:'3001',
        message:'获取列表失败'
    })
    }
})

router.get('/:id',(req,res)=>{
    const {id} = req.params
    BookModel.findById(id,(error,data)=>{
        if(error){
            res.json({
                status:'3001',
                message:'获取列表失败'
        })
        }else{
            res.json({
                status:'3000',
                data,
                message:'获取列表成功'
             })
        }
    })
})



router.post('/',(req,res)=>{
    const book = req.body
    BookModel.create(book,(error,data)=>{
        if(error){
        res.json({
            status:'3001',
            message:'获取列表失败'
        })
        }else{
            res.json({
            status:'3000',
            data,
            message:'获取列表成功'
            })
        }
    })
})


router.put('/',(req,res)=>{
    const book =req.body

    BookModel.updateOne({_id:book.id},book,(error,data)=>{
        if(error){
            res.json({
                status:'3001',
                message:'获取列表失败'
            })
        }else{
            res.json({
                status:'3000',
                data,
                message:'获取列表成功'
            })
        }
    })
})


router.delete('/',(req,res)=>{
    const {id} = req.query
    BookModel.deleteOne({_id:id},(error,data)=>{
        if(error){
            res.json({
                status:'3001',
                message:'获取列表失败'
            })
        }else{
            res.json({
                status:'3000',
                data,
                message:'获取列表成功'
            })
        }
    })
})

module.exports = router